/*
 * ActivateStationFrame.java
 *
 * Created on Jan 7, 2012, 10:27:49 PM
 */
package gui;

import java.util.List;

import javax.swing.JOptionPane;

import db.DatabaseManager;
import db.entity.Padbatch;
import db.entity.Padlot;
import db.entity.PadlotPK;

import util.Activity;
import util.Authentication;
import util.ErrorMessage;
/**
 *
 * @author suzann
 */
public class ActivateStationFrame extends javax.swing.JFrame {

    /** Creates new form ActivateStationFrame */
    public ActivateStationFrame() {
        _instance = this;
        initComponents();
        listPadLotID();
        getActivePadlotID();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jcbStation = new javax.swing.JComboBox();
        jcbPadLotID = new javax.swing.JComboBox();
        jbtActivate = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setMinimumSize(new java.awt.Dimension(237, 180));

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel1.setText("Station Name:");

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel2.setText("Pad Batch ID:");

        jcbStation.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "01", "02", "03", "04", "05", "06", "07" }));
        jcbStation.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	jcbStationActionPerformed(evt);
            }
        });
        
        jcbPadLotID.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jbtActivate.setText("Activate");
        jbtActivate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtActivateActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jLabel1)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(jcbStation, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jLabel2)
                            .addGap(18, 18, 18)
                            .addComponent(jcbPadLotID, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addComponent(jbtActivate))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jcbStation, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jcbPadLotID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jbtActivate)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-253)/2, (screenSize.height-140)/2, 253, 140);
    }// </editor-fold>
    
    private void jbtActivateActionPerformed(java.awt.event.ActionEvent evt) {  
	   // Validate Input 
	   if(jcbStation.getSelectedItem() == null)
	   {
	   	JOptionPane.showMessageDialog(null, "Missing Station Number. Please select a station.", "Validation Error", JOptionPane.ERROR_MESSAGE);
	   	return;
	   }
	   
	   if(jcbPadLotID.getSelectedItem() == null)
	   {
	   	JOptionPane.showMessageDialog(null, "Missing Pad Batch ID. Please select a pad batch ID.", "Validation Error", JOptionPane.ERROR_MESSAGE);
	   	return;
	   } 

	   // Retrieve and validate input               
	   String stationNo = jcbStation.getSelectedItem().toString();
	   String padLotID = jcbPadLotID.getSelectedItem().toString();
	   
	   DatabaseManager db = new DatabaseManager();
	   
	   if(db.listPolyByArmPadlot("L"+stationNo, padLotID) == null ||db.listPolyByArmPadlot("R"+stationNo, padLotID) == null)
	   {
		   String errMsg = "Polynomial for Station '"+stationNo+"' (";
		   if(db.listPolyByArmPadlot("L"+stationNo, padLotID) == null)
			   errMsg += "left ";
		   if(db.listPolyByArmPadlot("R"+stationNo, padLotID) == null)
			   errMsg += "right ";
		   
		   errMsg += "arm) and Pad Lot ID '" +padLotID+ "' not found. Please insert Polynomial value before activate station.";
		   ErrorMessage.displayError(ErrorMessage.WARNING_ERROR, false, "Validation Error", errMsg);
		   return;
	   }
	   
	   // Validate User
	   String username = null;
	   boolean valid = false;
	   do
	   {
		   username = Authentication.authenticateUser();
		   if(username.equals("Invalid"))
			   JOptionPane.showMessageDialog(this, "Your username is invalid.\nPlease enter your username again.", "Authentication Failure", JOptionPane.WARNING_MESSAGE);
		   else if (username.equals("Exit"))
			   return;
		   else
			   if (username != null)
				   valid = true;
	   }while(!valid);
        	   
	   // Update database: save into pad lot table
	   Integer padCount = db.getCurrentPadCount(padLotID, stationNo);

	   System.out.println(stationNo + " : " + padLotID + " : " + padCount);
	   Padlot pl = new Padlot();
	   PadlotPK pl_id = new PadlotPK();
	   pl_id.setPadLotId(padLotID);
	   pl_id.setStationName(stationNo);
	   pl.setId(pl_id);
	   pl.setPadCount((int) (padCount+1));
	   pl.setActive(1);
    
	   db.updatePadLot(pl);
	   Activity.log("Activate Pad Batch '"+padLotID+"' for Station "+stationNo, username, "");
    
	   JOptionPane.showMessageDialog(null, "Successfully activated Pad Batch.", "Activated Successfully", JOptionPane.PLAIN_MESSAGE);
    
    }        
    
    private void jcbStationActionPerformed(java.awt.event.ActionEvent evt) { 
    	getActivePadlotID();
    }
    
    private void getActivePadlotID()
    {
    	if(jcbStation.getSelectedItem() == null)
    		return;
    	
    	String stationName = jcbStation.getSelectedItem().toString();    	
    	DatabaseManager db = new DatabaseManager();
    	Padlot pItem = db.getActivePadlotByStationName(stationName);
    	if(pItem == null)
    	{
    		jcbPadLotID.setSelectedIndex(-1);
    		return ;
    	}

		jcbPadLotID.setSelectedIndex(-1);
    	String padLotID = pItem.getId().getPadLotId();
    	for(int i=0; i<jcbPadLotID.getItemCount(); i++ )
    	{
    		String padListItem = jcbPadLotID.getItemAt(i).toString();
    		if(padListItem.equals(padLotID))
    		{
    			jcbPadLotID.setSelectedIndex(i);
    			break;
    		}
    	}
    }
    
    private void listPadLotID()
    {
    	jcbPadLotID.removeAllItems(); 	
    	DatabaseManager db = new DatabaseManager();
    	List<Padbatch> pList = db.getPadBatchID();
    	for(Padbatch pItem : pList)
    	{    	 
    		jcbPadLotID.addItem(pItem.getPadBatchID());
    	}    	
    }
    
    public static void updatePadLotID()
    {
    	_instance.listPadLotID();
    }

    
    public void addNotify() {
        super.addNotify();
        // Buffer
        createBufferStrategy(2);           
        //BufferStrategy strategy = getBufferStrategy();
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ActivateStationFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ActivateStationFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ActivateStationFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ActivateStationFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new ActivateStationFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JButton jbtActivate;
    private javax.swing.JComboBox jcbPadLotID;
    private javax.swing.JComboBox jcbStation;
    // End of variables declaration
    
    // Programmer Declared Variables
    private static ActivateStationFrame _instance;
}
